<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left" @tap="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="header-title">设备设置</text>
      <view class="header-right"></view>
    </view>

    <!-- 设备信息 -->
    <view class="device-info" v-if="deviceInfo">
      <view class="info-item">
        <text class="label">设备名称</text>
        <input 
          class="input" 
          v-model="deviceInfo.de_name" 
          placeholder="请输入设备名称"
        />
      </view>
      
      <view class="info-item" @tap="selectDeviceType">
        <text class="label">设备类型</text>
        <view class="value-wrapper">
          <text class="value">{{ getDeviceTypeName(deviceInfo.de_model) }}</text>
          <text class="iconfont icon-right"></text>
        </view>
      </view>
      
      <view class="info-item">
        <text class="label">设备位置</text>
        <input 
          class="input" 
          v-model="deviceInfo.de_location" 
          placeholder="请输入设备位置"
        />
      </view>
      
      <view class="info-item">
        <text class="label">设备状态</text>
        <view class="status-wrapper">
          <view class="status" :class="getStatusClass(deviceInfo.de_status)">
            <view class="status-dot"></view>
            <text>{{ getStatusText(deviceInfo.de_status) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 设置选项 -->
    <view class="settings-list" v-if="deviceInfo">
      <view class="settings-group">
        <view class="settings-item" @tap="showDataSettings">
          <text class="item-label">数据设置</text>
          <text class="iconfont icon-right"></text>
        </view>
        
        <view class="settings-item" @tap="showAlertSettings">
          <text class="item-label">告警设置</text>
          <text class="iconfont icon-right"></text>
        </view>
        
        <view class="settings-item" @tap="showMaintenanceSettings">
          <text class="item-label">维护设置</text>
          <text class="iconfont icon-right"></text>
        </view>
      </view>
      
      <view class="settings-group">
        <view class="settings-item danger" @tap="showDeleteConfirm">
          <text class="item-label">删除设备</text>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-btn" @tap="saveSettings" v-if="deviceInfo">
      <text>保存设置</text>
    </view>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, onMounted } from 'vue';

// 设备信息
const deviceInfo = ref(null);

// 设备类型选项
const deviceTypes = [
  { id: 'sensor', name: '传感器' },
  { id: 'camera', name: '摄像头' },
  { id: 'controller', name: '控制器' },
  { id: 'irrigation', name: '灌溉' },
  { id: 'light', name: '照明' }
];

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page?.options || {};
  
  // 解析URL参数
  const params = {
    id: options.id,
    type: options.type,
    status: parseInt(options.status) || 0,
    name: decodeURIComponent(options.name || ''),
    location: decodeURIComponent(options.location || '')
  };
  
  console.log('获取到的页面参数:', params);
  return params;
};

// 获取设备信息
const getDeviceInfo = async (deviceId) => {
  try {
    uni.showLoading({ title: '加载中...' });
    
    const { result } = await uniCloud.callFunction({
      name: 'getDevice',
      data: { deviceId }
    });
    
    if (result.code === 0 && result.data) {
      // 使用云函数返回的数据更新设备信息
      deviceInfo.value = {
        _id: result.data._id,
        de_name: result.data.de_name,
        de_model: result.data.de_model,
        de_location: result.data.de_location,
        de_status: result.data.de_status,
        de_data: result.data.de_data || {},
        update_time: result.data.update_time
      };
      console.log('获取到的设备信息:', deviceInfo.value);
    } else {
      // 如果云函数获取失败，使用URL参数中的信息
      const params = getPageParams();
      deviceInfo.value = {
        _id: params.id,
        de_name: params.name,
        de_model: params.type,
        de_location: params.location,
        de_status: params.status,
        de_data: {},
        update_time: Date.now()
      };
      console.log('使用URL参数创建设备信息:', deviceInfo.value);
      
      uni.showToast({
        title: '获取设备信息失败，使用本地数据',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取设备信息失败:', error);
    // 如果发生错误，使用URL参数中的信息
    const params = getPageParams();
    deviceInfo.value = {
      _id: params.id,
      de_name: params.name,
      de_model: params.type,
      de_location: params.location,
      de_status: params.status,
      de_data: {},
      update_time: Date.now()
    };
    console.log('发生错误，使用URL参数创建设备信息:', deviceInfo.value);
    
    uni.showToast({
      title: '获取设备信息失败，使用本地数据',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 获取设备类型名称
const getDeviceTypeName = (type) => {
  const deviceType = deviceTypes.find(t => t.id === type);
  return deviceType ? deviceType.name : '未知类型';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '离线',
    1: '在线',
    2: '异常'
  };
  return statusMap[status] || '未知';
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    0: 'offline',
    1: 'online',
    2: 'warning'
  };
  return statusMap[status] || 'offline';
};

// 选择设备类型
const selectDeviceType = () => {
  uni.showActionSheet({
    itemList: deviceTypes.map(type => type.name),
    success: (res) => {
      deviceInfo.value.de_model = deviceTypes[res.tapIndex].id;
    }
  });
};

// 显示数据设置
const showDataSettings = () => {
  uni.showToast({
    title: '数据设置功能开发中',
    icon: 'none'
  });
};

// 显示告警设置
const showAlertSettings = async () => {
  try {
    // 更新设备状态为警告
    const { result } = await uniCloud.callFunction({
      name: 'updateDeviceStatus',
      data: {
        deviceId: deviceInfo.value._id,
        status: 2 // 警告状态
      }
    });
    
    if (result.code === 0) {
      deviceInfo.value.de_status = 2;
      uni.showToast({
        title: '已设置为警告状态',
        icon: 'success'
      });
    } else {
      throw new Error(result.message || '设置失败');
    }
  } catch (error) {
    console.error('设置警告状态失败:', error);
  uni.showToast({
      title: '设置失败',
    icon: 'none'
  });
  }
};

// 显示维护设置
const showMaintenanceSettings = async () => {
  try {
    // 如果设备已经是在线状态，显示提示
    if (deviceInfo.value.de_status === 1) {
      uni.showToast({
        title: '设备已经是在线状态',
        icon: 'none'
      });
      return;
    }

    // 显示确认对话框
    uni.showModal({
      title: '维护设置',
      content: '是否将设备状态设置为在线？',
      success: async (res) => {
        if (res.confirm) {
          await setDeviceOnline();
        }
      }
    });
  } catch (error) {
    console.error('维护设置操作失败:', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 设置设备为在线状态
const setDeviceOnline = async () => {
  try {
    uni.showLoading({ title: '正在设置...' });
    
    const { result } = await uniCloud.callFunction({
      name: 'updateDeviceStatus',
      data: {
        deviceId: deviceInfo.value._id,
        status: 1 // 在线状态
      }
    });
    
    if (result.code === 0) {
      // 更新本地设备状态
      deviceInfo.value.de_status = 1;
      
      uni.showToast({
        title: '设备已设为在线',
        icon: 'success'
      });
    } else {
      throw new Error(result.message || '设置失败');
    }
  } catch (error) {
    console.error('设置设备在线状态失败:', error);
  uni.showToast({
      title: '设置失败',
    icon: 'none'
  });
  } finally {
    uni.hideLoading();
  }
};

// 显示删除确认
const showDeleteConfirm = () => {
  // 如果设备在线，显示警告
  if (deviceInfo.value.de_status === 1) {
    uni.showModal({
      title: '警告',
      content: '设备当前在线，确定要删除该设备吗？',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          confirmDelete();
        }
      }
    });
  } else {
    // 设备离线，直接显示确认对话框
    uni.showModal({
      title: '确认删除',
      content: '确定要删除该设备吗？此操作不可恢复。',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          confirmDelete();
        }
      }
    });
  }
};

// 确认删除设备
const confirmDelete = async () => {
  try {
    uni.showLoading({
      title: '删除中...',
      mask: true
    });
    
    const { result } = await uniCloud.callFunction({
      name: 'deleteDevice',
      data: {
        deviceId: deviceInfo.value._id
      }
    });
    
    if (result.code === 0) {
      uni.showToast({
        title: '设备已删除',
        icon: 'success',
        duration: 1500
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        // 返回上一页并刷新设备列表
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        if (prevPage && prevPage.$vm.getDeviceList) {
          prevPage.$vm.getDeviceList();
        }
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(result.message || '删除失败');
    }
  } catch (error) {
    console.error('删除设备失败:', error);
    uni.showToast({
      title: error.message || '删除设备失败',
      icon: 'none',
      duration: 2000
    });
  } finally {
    uni.hideLoading();
  }
};

// 保存设置
const saveSettings = async () => {
  try {
    if (!deviceInfo.value.de_name?.trim()) {
      uni.showToast({
        title: '请输入设备名称',
        icon: 'none'
      });
      return;
    }

    uni.showLoading({ title: '保存中...' });
    
    const { result } = await uniCloud.callFunction({
      name: 'updateDevice',
      data: {
        deviceId: deviceInfo.value._id,
        updateData: {
          de_name: deviceInfo.value.de_name.trim(),
          de_model: deviceInfo.value.de_model,
          de_location: deviceInfo.value.de_location?.trim() || ''
        }
      }
    });
    
    if (result.code === 0) {
    uni.showToast({
      title: '设置已保存',
      icon: 'success'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
    } else {
      throw new Error(result.message || '保存失败');
    }
  } catch (error) {
    console.error('保存设置失败:', error);
    uni.showToast({
      title: '保存设置失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 生命周期钩子
onMounted(() => {
  const params = getPageParams();
  if (params.id) {
    getDeviceInfo(params.id);
  } else {
    uni.showToast({
      title: '设备ID无效',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  min-height: 100vh;
  padding-bottom: 120px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #4CAF50;
}

.header-left {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-left .iconfont {
  font-size: 20px;
  color: #ffffff;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
}

.header-right {
  width: 40px;
}

/* 设备信息 */
.device-info {
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 14px;
  color: #666666;
}

.input {
  flex: 1;
  text-align: right;
  font-size: 14px;
  color: #333333;
  padding: 0 10px;
}

.value-wrapper {
  display: flex;
  align-items: center;
}

.value {
  font-size: 14px;
  color: #333333;
  margin-right: 5px;
}

.icon-right {
  font-size: 14px;
  color: #999999;
}

.status-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status {
  display: flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.05);
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 3px;
  margin-right: 4px;
}

.status.online .status-dot {
  background-color: #4CAF50;
}

.status.offline .status-dot {
  background-color: #9E9E9E;
}

.status.warning .status-dot {
  background-color: #FF9800;
  animation: pulse 1.5s infinite;
}

.status text {
  font-size: 12px;
  color: #666666;
}

/* 设置列表 */
.settings-list {
  background-color: #ffffff;
}

.settings-group {
  margin-bottom: 10px;
}

.settings-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.settings-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 14px;
  color: #333333;
}

.settings-item.danger .item-label {
  color: #ff4d4f;
}

/* 保存按钮 */
.save-btn {
  position: fixed;
  left: 15px;
  right: 15px;
  bottom: 30px;
  height: 44px;
  background-color: #4CAF50;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn text {
  font-size: 16px;
  color: #ffffff;
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.5); opacity: 0.5; }
  100% { transform: scale(1); opacity: 1; }
}
</style>